package easier.fast.service.observer;

import androidx.annotation.CallSuper;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.Lifecycle.Event;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * @param <T> 观察者,同时关注activity生命周期,
 *            在请求时如果完成{@link #onNext(Object)}或者{@link #onError(Throwable)}停止观察
 *            ,还没有完成时,如果activity销毁那么同样取消订阅
 */
public class LifeObserver< T > implements Observer< T >, LifecycleObserver {

    private final Lifecycle mLifecycle;
    private Disposable mDisposable;

    public LifeObserver( Lifecycle lifecycle ) {

        mLifecycle = lifecycle;

        if ( lifecycle != null ) {
            lifecycle.addObserver( this );
        }
    }

    @CallSuper
    @Override
    public void onSubscribe( @NonNull Disposable d ) {

        mDisposable = d;
    }

    @Override
    public void onNext( T o ) {

    }

    @Override
    @CallSuper
    public void onError( @NonNull Throwable e ) {

        notifyFinished();
    }

    @Override
    @CallSuper
    public void onComplete() {

        notifyFinished();
    }

    @OnLifecycleEvent( Event.ON_DESTROY )
    @CallSuper
    public void onDestroy() {

        notifyFinished();
    }

    /**
     * 快捷方法:移除activity生命观察
     */
    @CallSuper
    protected void notifyFinished() {

        if ( mDisposable != null ) {
            mDisposable.dispose();
            mDisposable = null;
        }

        if ( mLifecycle != null ) {
            mLifecycle.removeObserver( this );
        }
    }
}
